import { loc } from '../../local';

const pad = (n) => n < 10 ? '0' + n : n;

// 2019-03-09
const loc_day = (v) => v ? pad(v.getFullYear()) + "-" + pad(v.getMonth() + 1) + "-" + pad(v.getDate()) : null;

// 2019
const loc_year = (v) => v ? pad(v.getFullYear()) : null;

// 20:33:09
const loc_time = (v) => v ? pad(v.getHours()) + ":" + pad(v.getMinutes()) + ":" + pad(v.getSeconds()) : null;

// 20:33
const loc_hm = (v) => v ? pad(v.getHours()) + ":" + pad(v.getMinutes()) : null;

// 2019-03-09T20:33:09Z
const loc_str = (v) => v ? loc_day(v) + "T" + loc_time(v) + "Z" : null;

const get_tag = (v) => `${pad(v.getFullYear())}${ pad(v.getMonth() + 1)}${pad(v.getDate())}${pad(v.getHours())}${pad(v.getMinutes())}${pad(v.getSeconds())}`;
const loc_tag = () => get_tag(new Date());

// 2019-03-09 20:33:09
const loc_dt = (v) => v ? loc_day(v) + " " + loc_time(v) : null;

// [9, 20, 18, 9小时20分钟18秒]
const get_time = (d) => {
    if (!d) {
        return [null, null, null, null];
    }

    let ret = "";

    let hour = 0;
    let minu = 0;
    let sec = 0;

    const h = parseInt(d/3600);
    if (h > 0) {
        hour = h;
        ret += h + loc("xs");
    }

    let r = d - h*3600;

    const m = parseInt(r/60);
    if (m > 0) {
        minu = m;
        ret += m + loc("fz");
    }

    r -= m*60;
    if (r > 0) {
        sec = r;
        ret += r + loc("m");
    }

    return [hour, minu, sec, ret];
};

const utc_day = (v) => v ? pad(v.getUTCFullYear()) + "-" + pad(v.getUTCMonth() + 1) + "-" + pad(v.getUTCDate()) : null;

// 20:33:09
const utc_time = (v) => v ? pad(v.getUTCHours()) + ":" + pad(v.getUTCMinutes()) + ":" + pad(v.getUTCSeconds()) : null;

// 2019-03-09 20:33:09
const utc_dt = (s) => {
    if (!s) {
        return "";
    }

    let tmp = new Date(s);
    return utc_day(tmp) + " " + utc_time(tmp);
};

// s + 8 hours
// 2019-03-09 20:33:09
const utc_8 = (s, t=8) => {
    let v = new Date(s);
    v.setTime(v.getTime() + t*60*60*1000);
    return utc_day(v) + " " + utc_time(v);
};

const start_day = (d) => {
    let v = new Date();
    if (d) {
        v.setDate(v.getDate() - d);
    }

    v = loc_day(v) + " 00:00:00";
    return new Date(v);
};

const end_day = () => {
    let v = new Date();
    v = loc_day(v) + " 23:59:59";
    return new Date(v);
};

const get_week = (i) => "星期" + "日一二三四五六".charAt(i);

// ["2019-03-09", "20:33:09", "星期一"]
const loc_week = () => {
    const v = new Date();
    return [loc_day(v), loc_time(v), get_week(v.getDay())];
};

export {pad, get_time, start_day, end_day, loc_hm, loc_time, loc_day, loc_str, loc_dt,
    get_week, loc_tag, loc_week, utc_8, utc_dt,
    utc_time,
    loc_year};
